package com.example.contactfragment;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.boyuan.huijiaoyu.AccountLoginActivity;
import com.boyuan.huijiaoyu.BaseActivity;
import com.boyuan.huijiaoyu.ColorHolderApplication;
import com.boyuan.huijiaoyu.R;
import com.easemob.EMCallBack;
import com.easemob.EMValueCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMGroupManager;
import com.easemob.util.EMLog;
import com.easemob.util.HanziToPinyin;
import com.example.combinebitmap.NewGroupActivity;
import com.example.huanxin.ChatActivity;
import com.example.huanxin.Constant;
import com.example.huanxin.more.HXSDKHelper;
import com.example.huanxin.more.User2;
import com.example.huanxin.more.UserDao;
import com.example.newfragment.DetailPerson;
import com.magicsoft.app.helper.SharePreferenceHelper;
import com.magicsoft.app.helper.ToastHelper;
import com.magicsoft.app.wcf.listener.GetOneRecordListener;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 我的群组
 */
public class HomeContactMyGroupActivity extends Activity implements
		OnClickListener {

	private LinearLayout lin_back;
	ArrayList<MyGroup> groups = new ArrayList<MyGroup>();
	private ContactGroupService contactgroupService;
	MyAdapter adapter;
	String username;
	String mima;
	private boolean progressShow;
	public boolean isrequestok = false;
	private ListView mListview;
	String id;
	private GroupNameChangeReceive groupNameChangeReceive;
	private GroupUpdtatReceive groupUpdtatReceive;
	private String title;
	private DisplayImageOptions options;
	private ImageLoader imageLoader;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home_contact_my_group);
		SharedPreferences sp = this.getSharedPreferences("a.xml", 0);
		username = sp.getString("username", "18850198097");
		id = sp.getString("id", "");
		mima = "" + username.substring(5, username.length());
		imageLoader = ImageLoader.getInstance();
		prepareView();
		getGroupsListCache();
		getMyGroup();
		registerGroupNameReceiver();
		RegisterGroupUpdataReceiver();
//		new Handler().postDelayed(new Runnable() {
//
//			@Override
//			public void run() {
//
//				if (isrequestok == true) {
//					return;
//				} else {
//					new Handler().postDelayed(this, 1000);
//				}
//			}
//		}, 1000);
	}
	
	private void registerGroupNameReceiver() {
		groupNameChangeReceive = new GroupNameChangeReceive();
		IntentFilter filter = new IntentFilter();
		filter.addAction("name_group");
		registerReceiver(groupNameChangeReceive, filter);
	}
	
	class GroupNameChangeReceive extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			getMyGroup();
		}
	}
	
	private void RegisterGroupUpdataReceiver(){
		groupUpdtatReceive = new GroupUpdtatReceive();
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction("uptatagroup");
		registerReceiver(groupUpdtatReceive, intentFilter);
	}
	
	class GroupUpdtatReceive extends BroadcastReceiver{

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			getMyGroup();
		}
	}
	
	@Override
	protected void onDestroy() {
		unregisterReceiver(groupNameChangeReceive);
		unregisterReceiver(groupUpdtatReceive);
		super.onDestroy();
	}

	private void getGroupsListCache() {
		groups.clear();
		ArrayList<MyGroup> groupsList = SharePreferenceHelper
				.getGroupsList(this, id);
		if (groupsList.size() > 0) {
			groups.addAll(groupsList);
			adapter.notifyDataSetChanged();
		}
	}


	private void chat(final int i) {

		progressShow = true;
		final ProgressDialog pd = new ProgressDialog(this);
		pd.setCanceledOnTouchOutside(false);
		pd.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				progressShow = false;
			}
		});
		pd.setMessage(getString(R.string.Is_landing));
		pd.show();

		final long start = System.currentTimeMillis();
		SharedPreferences sp = getSharedPreferences("a.xml", 0);
		String username = sp.getString("username", "18030095903");
		String mima = "" + username.substring(5, username.length());

		EMChatManager.getInstance().login(username, mima, new EMCallBack() {

			@Override
			public void onSuccess() {
				if (!progressShow) {
					return;
				}

				try {
					// ** manually load all local groups and
					EMGroupManager.getInstance().loadAllGroups();
					EMChatManager.getInstance().loadAllConversations();
					initializeContacts();
					asyncFetchContactsFromServer();
				} catch (Exception e) {
					e.printStackTrace();
					runOnUiThread(new Runnable() {
						public void run() {
							pd.dismiss();
							ColorHolderApplication.getInstance().logout(null);
							Toast.makeText(getApplicationContext(),
									R.string.login_failure_failed, 1).show();
						}
					});
					return;
				}
				boolean updatenick = EMChatManager.getInstance()
						.updateCurrentUserNick(
								ColorHolderApplication.currentUserNick.trim());
				if (!updatenick) {
				}
				if (!isFinishing() && pd.isShowing()) {
					pd.dismiss();
				}

				Intent intent = new Intent(HomeContactMyGroupActivity.this, ChatActivity.class);
				intent.putExtra("chatType", ChatActivity.CHATTYPE_GROUP);
				intent.putExtra("groupId", groups.get(i).groupid);
				intent.putExtra("groupName", groups.get(i).groupname);
				intent.putExtra("caseid", groups.get(i).getCaseid());
				intent.putExtra("back", "群组");
				startActivityForResult(intent, 0);
//				finish();
			}

			private void asyncFetchContactsFromServer() {

				HXSDKHelper.getInstance().asyncFetchContactsFromServer(
						new EMValueCallBack<List<String>>() {

							@Override
							public void onSuccess(List<String> usernames) {
								Context context = HXSDKHelper.getInstance()
										.getAppContext();

								Map<String, User2> userlist = new HashMap<String, User2>();
								for (String username : usernames) {
									User2 user = new User2();
									user.setUsername(username);
									setUserHearder(username, user);
									userlist.put(username, user);
								}
								User2 newFriends = new User2();
								newFriends
										.setUsername(Constant.NEW_FRIENDS_USERNAME);
								String strChat = context
										.getString(R.string.Application_and_notify);
								newFriends.setNick(strChat);

								userlist.put(Constant.NEW_FRIENDS_USERNAME,
										newFriends);
								User2 groupUser = new User2();
								String strGroup = context
										.getString(R.string.group_chat);
								groupUser.setUsername(Constant.GROUP_USERNAME);
								groupUser.setNick(strGroup);
								groupUser.setHeader("");
								userlist.put(Constant.GROUP_USERNAME, groupUser);

								User2 chatRoomItem = new User2();
								String strChatRoom = context
										.getString(R.string.chat_room);
								chatRoomItem.setUsername(Constant.CHAT_ROOM);
								chatRoomItem.setNick(strChatRoom);
								chatRoomItem.setHeader("");
								userlist.put(Constant.CHAT_ROOM, chatRoomItem);

								ColorHolderApplication.getInstance()
										.setContactList(userlist);
								UserDao dao = new UserDao(context);
								List<User2> users = new ArrayList<User2>(
										userlist.values());
								dao.saveContactList(users);

								HXSDKHelper.getInstance()
										.notifyContactsSyncListener(true);

								if (HXSDKHelper.getInstance()
										.isGroupsSyncedWithServer()) {
									HXSDKHelper.getInstance()
											.notifyForRecevingEvents();
								}

							}

							@Override
							public void onError(int error, String errorMsg) {
								HXSDKHelper.getInstance()
										.notifyContactsSyncListener(false);
							}

						});

			}

			private void setUserHearder(String username, User2 user) {
				String headerName = null;
				if (!TextUtils.isEmpty(user.getNick())) {
					headerName = user.getNick();
				} else {
					headerName = user.getUsername();
				}
				if (username.equals(Constant.NEW_FRIENDS_USERNAME)) {
					user.setHeader("");
				} else if (Character.isDigit(headerName.charAt(0))) {
					user.setHeader("#");
				} else {
					user.setHeader(HanziToPinyin.getInstance()
							.get(headerName.substring(0, 1)).get(0).target
							.substring(0, 1).toUpperCase());
					char header = user.getHeader().toLowerCase().charAt(0);
					if (header < 'a' || header > 'z') {
						user.setHeader("#");
					}
				}
			}

			private void initializeContacts() {
				Map<String, User2> userlist = new HashMap<String, User2>();
				User2 newFriends = new User2();
				newFriends.setUsername(Constant.NEW_FRIENDS_USERNAME);
				String strChat = getResources().getString(
						R.string.Application_and_notify);
				newFriends.setNick(strChat);

				userlist.put(Constant.NEW_FRIENDS_USERNAME, newFriends);
				User2 groupUser = new User2();
				String strGroup = getResources().getString(R.string.group_chat);
				groupUser.setUsername(Constant.GROUP_USERNAME);
				groupUser.setNick(strGroup);
				groupUser.setHeader("");
				userlist.put(Constant.GROUP_USERNAME, groupUser);
				ColorHolderApplication.getInstance().setContactList(userlist);
				UserDao dao = new UserDao(HomeContactMyGroupActivity.this);
				List<User2> users = new ArrayList<User2>(userlist.values());
				dao.saveContactList(users);

			}

			@Override
			public void onProgress(int progress, String status) {
			}

			@Override
			public void onError(final int code, final String message) {
				if (!progressShow) {
					return;
				}
				runOnUiThread(new Runnable() {
					public void run() {
						pd.dismiss();
					}
				});
			}
		});
	}

	private void getMyGroup() {

		if (contactgroupService == null) {
			contactgroupService = new ContactGroupService(this);
		}
		contactgroupService.getMynormalgroup(username, new GetOneRecordListener<List<MyGroup>>() {

			@Override
			public void onFinish(List<MyGroup> data) {
				groups.clear();
				if (data != null && data.size() >= 0) {
					groups.addAll(data);
					SharePreferenceHelper.saveGroupsList(HomeContactMyGroupActivity.this, id, data);
					isrequestok = true;
				}
				adapter.notifyDataSetChanged();
			}

			@Override
			public void onFailed(String Message) {
				
			}
		});
	}

	private void prepareView() {

		lin_back = (LinearLayout) findViewById(R.id.lin_back);
		lin_back.setOnClickListener(this);

		mListview = (ListView) findViewById(R.id.listView1);
		adapter = new MyAdapter();
		mListview.setAdapter(adapter);
		mListview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					final int arg2, long arg3) {
//				if(isrequestok){
					chat(arg2);
//				}else{
//					ToastHelper.showMsg(HomeContactMyGroupActivity.this, "网络连接异常", false);
//				}

			}
		});
	}

	class MyAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return groups.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			View inflate = getLayoutInflater().inflate(R.layout.list_mygroup,
					null);
			ImageView image = (ImageView) inflate.findViewById(R.id.image_casegroup);
			options = new DisplayImageOptions.Builder()
			.showImageOnLoading(R.drawable.default_header)
			.showImageForEmptyUri(R.drawable.default_header)
			.showImageOnFail(R.drawable.default_header).cacheInMemory(true)
			.cacheOnDisc(true).considerExifParams(true).build();
			String uri = com.magicsoft.constant.Constant.photourl + groups.get(arg0).groupid;
			imageLoader.displayImage(uri, image, options);
			TextView tv_name = (TextView) inflate.findViewById(R.id.groupname);
			tv_name.setText(groups.get(arg0).groupname);
			tv_name.setTextColor(Color.BLACK);
			return inflate;
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.lin_back:
			finish();
			break;
		default:
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (data != null) {
			if (requestCode == 100 && resultCode == 200) {
				getMyGroup();
			}
		}
	}

}
